#include "dialog.h"

#include <QApplication>
#include <QFile>
#include <QDebug>
#include <QTextCodec>
#include <mainwindow.h>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>
#include <QList>
#include <QHash>
#include <QVariant>


#include <QCoreApplication>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QHash>

#include "emaildialog.h"
#include "mainwindow.h"
#include "dialog.h"


void processJson(const QJsonValue& val, QVariant& result)
{
    if (val.isObject()) {
            QJsonObject obj = val.toObject();
            QHash<QString, QVariant> hash;
            for (const QString& key : obj.keys()) {
                QVariant subResult;
                processJson(obj.value(key), subResult);
                hash.insert(key, subResult);
            }
            result = hash;
        } else if (val.isArray()) {
            QJsonArray array = val.toArray();
            QVariantList list;
            for (const QJsonValue& itemVal : array) {
                QVariant subResult;
                processJson(itemVal, subResult);
                list.append(subResult);
            }
            result = list;
        } else {
            result = val.toVariant();
        }
}

bool compareTimestamp(const QHash<QString, QVariant>& h1, const QHash<QString, QVariant>& h2) {
    return h1.value("timestamp").toLongLong() < h2.value("timestamp").toLongLong();
}

// 拷贝
void List_to_ListHash(const QVariantList &dataList, QList<QHash<QString, QVariant>> &sersonDataHashList)
{
    for(const auto &data : dataList)
    {
        QVariantMap dataMap = data.toMap();
        QHash<QString, QVariant> dataHash;
        for(const QString &key : dataMap.keys())
        {
            dataHash.insert(key, dataMap.value(key));
        }
        sersonDataHashList.append(dataHash);
    }
}

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);



#if 0
    QString jsonString = "{\"code\":200,\"data\":{\"home_name\":\"\\u4e00\\u5bb6\\u56db\\u53e3\",\"users\":[{\"user_email\":\"227673@qq.com\",\"user_id\":2,\"user_name\":\"lfy2\",\"user_permission\":0,\"user_status\":\"OFF\"}]},\"message\":\"Home members retrieved successfully\"}";

       QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
       if (jsonDoc.isNull()) {
           qDebug() << "Failed to parse JSON";
           return -1;
       }

       QVariantMap map = jsonDoc.toVariant().toMap();

//       qDebug() << "Map字典: " << map.values();

       qDebug() << "code:" << map.value("code").toInt();
       qDebug() << "message:" << map.value("message").toString();

       QVariantMap dataMap = map.value("data").toMap();
       qDebug() << "home_name:" << dataMap.value("home_name").toString();

       QVariantList userList = dataMap.value("users").toList();
       for (const auto &user : userList) {
           QVariantMap userMap = user.toMap();
           qDebug() << userMap.value("user_email").toString()
                    << userMap.value("user_id").toInt()
                    << userMap.value("user_name").toString()
                    << userMap.value("user_permission").toInt()
                    << userMap.value("user_status").toString();
       }
#elif 0

    QString jsonString = "{\"code\":200,\"data\":{\"home_name\":\"\\u4e00\\u5bb6\\u56db\\u53e3\",\"users\":[{\"user_email\":\"227673@qq.com\",\"user_id\":2,\"user_name\":\"lfy2\",\"user_permission\":0,\"user_status\":\"OFF\"}]},\"message\":\"Home members retrieved successfully\"}";

        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
        if (jsonDoc.isNull()) {
            qDebug() << "Failed to parse JSON";
            return -1;
        }

        QJsonObject jsonObj = jsonDoc.object();
        QHash<QString, QVariant> hash;

        for (const QString &key : jsonObj.keys()) {
            QJsonValue val = jsonObj.value(key);
            if (val.isObject()) {
                QJsonObject obj = val.toObject();
                QHash<QString, QVariant> subHash;
                for (const QString &subKey : obj.keys()) {
                    QJsonValue subVal = obj.value(subKey);
                    if (subVal.isArray()) {
                        QJsonArray array = subVal.toArray();
                        QList<QHash<QString, QVariant>> list;
                        for (const auto &itemVal : array) {
                            QJsonObject itemObj = itemVal.toObject();
                            QHash<QString, QVariant> itemHash;
                            for (const QString &itemKey : itemObj.keys()) {
                                itemHash.insert(itemKey, itemObj.value(itemKey).toVariant());
                            }
                            list.append(itemHash);
                        }
                        QVariantList varList;
                        subHash.insert(subKey, list);
                    } else {
                        subHash.insert(subKey, subVal.toVariant());
                    }
                }
                hash.insert(key, subHash);
            } else if (val.isArray()) {
                QJsonArray array = val.toArray();
                QList<QHash<QString, QVariant>> list;
                for (const auto &itemVal : array) {
                    QJsonObject itemObj = itemVal.toObject();
                    QHash<QString, QVariant> itemHash;
                    for (const QString &itemKey : itemObj.keys()) {
                        itemHash.insert(itemKey, itemObj.value(itemKey).toVariant());
                    }
                    list.append(itemHash);
                }
                hash.insert(key, list);
            } else {
                hash.insert(key, val.toVariant());
            }
        }

        // 输出 QHash 中的数据
        qDebug() << "code:" << hash.value("code").toInt();
        qDebug() << "message:" << hash.value("message").toString();

        QHash<QString, QVariant> dataHash = hash.value("data").toHash();
        qDebug() << "home_name:" << dataHash.value("home_name").toString();

        QList<QHash<QString, QVariant>> userList = dataHash.value("users").toList();
        for (const auto &user : userList) {
            qDebug() << user.value("user_email").toString()
                     << user.value("user_id").toInt()
                     << user.value("user_name").toString()
                     << user.value("user_permission").toInt()
                     << user.value("user_status").toString();
        }
#elif 0
    QString jsonString = "{\"code\":200,\"data\":{\"home_name\":\"\\u4e00\\u5bb6\\u56db\\u53e3\",\"users\":[{\"user_email\":\"227673@qq.com\",\"user_id\":2,\"user_name\":\"lfy2\",\"user_permission\":0,\"user_status\":\"OFF\"}]},\"message\":\"Home members retrieved successfully\"}";

        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
        if (jsonDoc.isNull()) {
            qDebug() << "Failed to parse JSON";
            return -1;
        }

        QJsonValue jsonVal(jsonDoc.object());

        QVariantList result;
        processJson(jsonVal, result);

        QHash<QString, QVariant> hash = result.at(0).toHash();

        // 输出 QHash 中的数据
        qDebug() << "code:" << hash.value("code").toInt();
        qDebug() << "message:" << hash.value("message").toString();

        QHash<QString, QVariant> dataHash = hash.value("data").toHash();
        qDebug() << "home_name:" << dataHash.value("home_name").toString();

        QList<QHash<QString, QVariant>> userList = dataHash.value("users").toList();
        for (const auto& user : userList) {
            qDebug() << user.value("user_email").toString()
                     << user.value("user_id").toInt()
                     << user.value("user_name").toString()
                     << user.value("user_permission").toInt()
                     << user.value("user_status").toString();
        }
#elif 0000000000000000000000000000000000000000000000
//    QString jsonString = "{\"code\":200,\"data\":{\"home_name\":\"\\u4e00\\u5bb6\\u56db\\u53e3\",\"users\":[{\"user_email\":\"227673@qq.com\",\"user_id\":2,\"user_name\":\"lfy2\",\"user_permission\":0,\"user_status\":\"OFF\"}]},\"message\":\"Home members retrieved successfully\"}";
    QString jsonString = "{\"code\":200,\"data\":{\"home_name\":\"\u4e00\u5bb6\u4e94\u53e3\",\"users\":[{\"user_email\":\"22767@qq.com\",\"user_id\":3,\"user_name\":\"lfy3\",\"user_permission\":0,\"user_status\":\"OFF\"},{\"user_email\":\"22@qq.com\",\"user_id\":4,\"user_name\":\"lfy\",\"user_permission\":0,\"user_status\":\"ON\"},{\"user_email\":\"2209536340@qq.com\",\"user_id\":5,\"user_name\":\"lfy123\",\"user_permission\":0,\"user_status\":\"OFF\"},{\"user_email\":\"22095363d65740@qq.com\",\"user_id\":6,\"user_name\":\"lfy1234\",\"user_permission\":0,\"user_status\":\"OFF\"}]},\"message\":\"Home members retrieved successfully\"}";
        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
        if (jsonDoc.isNull()) {
            qDebug() << "Failed to parse JSON";
            return -1;
        }

        QVariantMap map = jsonDoc.toVariant().toMap();

        qDebug() << "code:" << map.value("code").toInt();
        qDebug() << "message:" << map.value("message").toString();

        QVariantMap dataMap = map.value("data").toMap();
        qDebug() << "home_name:" << dataMap.value("home_name").toString();

        QVariantList userList = dataMap.value("users").toList();
        QList<QHash<QString, QVariant>> userHashList;

        for (const auto &user : userList) {
            QVariantMap userMap = user.toMap();
            QHash<QString, QVariant> userHash;
            for (const QString &key : userMap.keys()) {
                userHash.insert(key, userMap.value(key));
            }
            userHashList.append(userHash);
        }

        for (const auto &user : userHashList) {
            qDebug() << user.value("user_email").toString()
                     << user.value("user_id").toInt()
                     << user.value("user_name").toString()
                     << user.value("user_permission").toInt()
                     << user.value("user_status").toString();
        }
#elif 0
    QString jsonString = "{\"code\":200,\"data\":[{\"humidity\":22.3,\"temperature\":13.5,\"timestamp\":\"Wed, 06 Dec 2023 16:47:05 GMT\"},{\"humidity\":22.3,\"temperature\":13.5,\"timestamp\":\"Wed, 06 Dec 2023 16:47:13 GMT\"},{\"humidity\":22.3,\"temperature\":13.5,\"timestamp\":\"Wed, 06 Dec 2023 16:47:14 GMT\"},{\"humidity\":22.3,\"temperature\":13.5,\"timestamp\":\"Wed, 06 Dec 2023 16:47:15 GMT\"},{\"humidity\":22.3,\"temperature\":13.5,\"timestamp\":\"Wed, 06 Dec 2023 16:47:15 GMT\"},{\"humidity\":22.3,\"temperature\":13.5,\"timestamp\":\"Wed, 06 Dec 2023 16:47:16 GMT\"}],\"message\":\"Sensor data retrieved successfully\"}";

        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonString.toUtf8());
        if (jsonDoc.isNull()) {
            qDebug() << "Failed to parse JSON";
            return -1;
        }

//        QJsonValue jsonVal(jsonDoc.object());

//        QVariantList result;
//        QVariant re = result;
//        processJson(jsonVal, re);



//        QHash<QString, QVariant> hash = result.at(0).toHash();

        QVariantMap map = jsonDoc.toVariant().toMap();

        // 输出 QHash 中的数据
        qDebug() << "code:" << map.value("code").toInt();
        qDebug() << "message:" << map.value("message").toString();

        QVariantList dataList = map.value("data").toList();
        QList<QHash<QString, QVariant>> sersonDataHashList;

        // 拷贝
        List_to_ListHash(dataList, sersonDataHashList);


        for (const auto& data : sersonDataHashList) {
            qDebug() << "humidity:" << data.value("humidity").toDouble()
                     << "temperature:" << data.value("temperature").toDouble()
                     << "timestamp:" << data.value("timestamp").toString();
        }


//    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));
//    QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
//    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));

//    QString defaultDir = QCoreApplication::applicationDirPath();
//    QFile qss(defaultDir+"/login.qss");
//    if( qss.open(QFile::ReadOnly))
//    {
//        qDebug()<<endl<<"open success";
//        QString style = QLatin1String(qss.readAll());
//        a.setStyleSheet(style);
//        qss.close();
//    }
//    else
//    {
//        qDebug()<<endl<<"Open failed";
//    }

#elif 0
//    Dialog w;
//    w.show();
#else
//    MainWindow m;
//    m.show();
#endif
//    EmailDialog e;
//    e.show();

    MainWindow mainWindow;
    Dialog login;

//    QObject::connect(&loginWidget, &Dialog::user_info, [&mainWindow](const QString& username){
//            // 在这里处理登录完成后的操作，例如将用户名传递给主窗口
//            mainWindow.handleLoginCompleted(username);
//        });
    // 建立信号和槽的连接
    QObject::connect(&login, &Dialog::user_info, [&](const QString username){
        mainWindow.handleLoginCompleted(username);

    });

    if(login.exec() == QDialog::Accepted)
    {
        mainWindow.show();
    } else {
        return 0;
    }


//    if(login.exec() == QDialog::Accepted)
//    {
//        mainWindow.show();
//    } else {
//        mainWindow.close();
//    }
//    QObject::connect(&login, &Dialog::loginWindowClosed, [&]() {

//        // 显示主窗口
//        mainWindow.show();
//    });

//    login.show();

//    // 进入事件循环，等待用户登录成功
//    QEventLoop loop;
//    QObject::connect(&login, &Dialog::accepted, &loop, &QEventLoop::quit);
//    loop.exec();

//    // 显示主窗口
//    mainWindow.show();


//    if(QDialog::Accepted == login.exec())
//    {
//       QStringList user_info = login.getLoginUserInfo();
//       m.do_show_user_info(user_info);
//       m.show();
//    }



    return a.exec();
}
